#include <stdio.h>
#include <memory>
#include "smart/player.hpp"
#include "clocker/timer.hpp"
#include "../mpp/smart/h264_file_nalu_pars.h"
#include "../mpp/smart/smart_mpp_decoder.hpp"

int main(const int argc, const char* argv[])
{
    if (argc != 4) {
        log_error("para failed, simple: ./test_run demo.h264 1920 1080");
        exit(EXIT_FAILURE);
    }

    uint8_t* tmp_buf = (uint8_t*)malloc(3840*2160*2);
    Timer* timer = Timer::get_instance();

    std::unique_ptr<Player> player = std::make_unique<Player>(atoi(argv[2]), atoi(argv[3]));

    SmartMppDecoder mpp_dec(MPP_VIDEO_CodingAVC);
    H264FileNaluPars h264_nalu;
    h264_nalu.init(argv[1], H264FileNaluPars::FMT_H264);

    log_info("ready ...");
    getchar();
    while (true) {

        // 从文件获取编码文件单元
        std::vector<uint8_t> h264_data = h264_nalu.get_nalu_frame();
        while (h264_data.size() < 1000) {
            std::vector<uint8_t> tmp_vec = h264_nalu.get_nalu_frame();
            if (tmp_vec.size() <= 0) {
                log_debug("h264 file read end.");
                exit(EXIT_FAILURE);
            }
            h264_data.insert(h264_data.end(), tmp_vec.begin(), tmp_vec.end());
        }

        // 解码为图像数据
        
        mpp_dec.sync_decoding(h264_data.data(), h264_data.size(), [&timer, &tmp_buf, &player](uint8_t* frm_buf, uint32_t frm_len){
            if (frm_buf == NULL || frm_len <= 0) {
                log_error("get decode file NULL.");
                return;
            }
            log_info("src tmp_buf: %p, frm_buf: %p.", tmp_buf, frm_buf);
#if 0
            player->write_image(RK_FORMAT_YCbCr_420_SP, frm_buf);
            player->player_image();
#else
            memcpy(tmp_buf, frm_buf, frm_len);
            player->write_image(RK_FORMAT_YCbCr_420_SP, tmp_buf);
            player->player_image();
#endif
        });

        

        log_info("----------------------memcpy timer:%ldus.", timer->end());
        timer->begin();
    }

    return 0;
}